import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'val_ui_kit_base_decoration.dart';
import 'val_ui_kit_dialog_impl.dart';

class ValLoaderToast {

  static void show(String msg, {bool hideProgress = true}) {
    if (hideProgress) ValUIKitDialogImpl.hideProgress();
    ValLoaderBaseToast().showNormal(Get.overlayContext!, msg);
  }

}


class ValLoaderBaseToast {
  ValLoaderBaseToast._();

  static ValLoaderBaseToast? _instance;

  factory ValLoaderBaseToast() {
    return _instance ??= ValLoaderBaseToast._();
  }

  Queue<ValToastView> curShow = Queue();

  ///默认显示一个toast
  void showNormal(BuildContext context, String msg) =>
      show(context, ValToastView(msg));

  ///显示
  void show(BuildContext context, ValToastView toast) async {
    if (curShow.contains(toast)) return;
    if (curShow.isNotEmpty) {
      curShow.add(toast);
      return;
    }
    curShow.add(toast);

    ValToastView temp;
    while (curShow.isNotEmpty) {
      temp = curShow.first;
      OverlayEntry entry = OverlayEntry(
          builder: (context) => ValToastComponent(temp.msg, temp.alignment));
      Overlay.of(context).insert(entry);
      Future future = Future.delayed(temp.duration, () {
        entry.remove();
        curShow.removeFirst();
      });
      await future;
    }
  }
}


class ValToastView {
  ValToastView(
      this.msg, {
        this.duration = const Duration(milliseconds: 1500),
        this.alignment = Alignment.center,
      });

  final String msg;
  final Duration duration;
  final AlignmentGeometry alignment;

  @override
  int get hashCode =>
      Object.hash(msg, duration.toString(), alignment.toString());

  @override
  bool operator ==(Object other) {
    return other is ValToastView &&
        other.msg == msg &&
        other.duration.toString() == duration.toString() &&
        other.alignment.toString() == alignment.toString();
  }
}


class ValToastComponent extends StatelessWidget {
  const ValToastComponent(this.msg, this.alignment, {Key? key})
      : super(key: key);
  final String msg;
  final AlignmentGeometry alignment;

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: alignment,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 30),
        child: Material(
          elevation: 2,
          color: Colors.transparent,
          shape:
          RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
            decoration: ValUIKitBaseDecoration.getShapeDecoration(
                bg: const Color(0x99000000), radius: 10),
            child: Text(
              msg,
              style: const TextStyle(fontSize: 15, color: Color(0xFFFFFFFF)),
            ),
          ),
        ),
      ),
    );
  }
}